package org.zp.handler;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.omg.CORBA.Any;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.zp.dto.GetMyLogisticsDto;
import org.zp.dto.GetexpressSunDto;
import org.zp.dto.PutdocEditdto;
import org.zp.dto.SendStateDto;
import org.zp.pojo.AdminInfo;
import org.zp.pojo.ExpressInfo;
import org.zp.pojo.NEInfo;
import org.zp.pojo.UserInfo;
import org.zp.pojo.UserOldInfo;
import org.zp.service.AddressService;
import org.zp.service.AdminLogInfoService;
import org.zp.service.CheckInfoService;
import org.zp.service.ExpressInfoService;
import org.zp.service.NetWorkInfoService;
import org.zp.service.UserInfoService;
import org.zp.util.Ajax;
import org.zp.vo.AdminMoneySunVo;
import org.zp.vo.ExperssVo;
import org.zp.vo.NetWithAdminVo;
import org.zp.vo.NetWorkMoneySunVo;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
/**
 * 快件相关业务
 * @FileName LogisticsHandler.java
 * @author zp
 * @package 2020年8月9日
 * @TODO
 */
@RestController
public class LogisticsHandler {
@Resource
private ExpressInfoService e;
@Resource
private UserInfoService u;
@Resource
private CheckInfoService c;
@Resource
private NetWorkInfoService n;
@Resource
private AddressService a;
@Resource
private AdminLogInfoService log;

private String checkurl = "快件审核表";
private String sendurl = "快件寄送表";
/**
 * 获得物流的列表
 * @param dto
 * @param req
 * @param resp
 */
@GetMapping("getLogistics.act")
private void getLogistics(GetMyLogisticsDto dto,HttpServletRequest req, HttpServletResponse resp) {
	
	Integer startpage = Integer.parseInt(dto.getStartpage());
	Integer limitpage = Integer.parseInt(dto.getLimitpage());
	Long typeid = (long) Integer.parseInt(dto.getTypeid());
	Long check = (long) Integer.parseInt(dto.getCheck());
	String start = dto.getStart();//起始日期
	String end = dto.getEnd();//结束日期

if (typeid==0) {
	typeid = null;
}
if (check==0) {
	check = null;
}
if (start.equals("")) {
		start = null;
}
if (end.equals("")) {
	end = null;
}
if (start!=null&&end!=null) {
	DateFormat df = new SimpleDateFormat("yyyy-MM-dd");//日期格式处理
     try {
			Date star = df.parse(start);
			Date endd = df.parse(end);
			if (star.getTime()>endd.getTime()){//比较时间的大小
				Ajax.error(resp,"时间有误",10001);
				return;
         }
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
}


System.out.println("------------check"+check);
System.out.println("------------start"+start);
System.out.println("------------end"+end);
System.out.println("------------startpage"+startpage);
System.out.println("------------limitpage"+limitpage);


List<ExpressInfo> list = e.getLogistics(typeid,check,start,end,startpage,limitpage);

for (int i = 0; i < list.size(); i++) { 
	System.out.println("已分页"+list.get(i).geteId());	
}


System.out.println("方法已走完");
PageInfo<ExpressInfo>pageInfo = new PageInfo<ExpressInfo>(list);
Integer count = (int) pageInfo.getTotal();
System.out.println("多条件count:"+count);
Ajax.success(resp, "list","count", list,count);
}

/**
 * 审核通过的快件的多条件查询
 * @param dto
 * @param req
 * @param resp
 */
@GetMapping("selectCheckFile.act")
private void selectCheckFile(GetMyLogisticsDto dto,HttpServletRequest req, HttpServletResponse resp) {
	
	Integer startpage = Integer.parseInt(dto.getStartpage());
	Integer limitpage = Integer.parseInt(dto.getLimitpage());
	
	
	String start = dto.getStart();//起始日期
	String end = dto.getEnd();//结束日期
	String username = dto.getUsername();
	String title = dto.getTitle();
	
if (username.equals("")) {
	username = null;
}
if (title.equals("")) {
	title = null;
}
if (start.equals("")) {
		start = null;
}
if (end.equals("")) {
	end = null;
}
if (start!=null&&end!=null) {
	DateFormat df = new SimpleDateFormat("yyyy-MM-dd");//日期格式处理
     try {
			Date star = df.parse(start);
			Date endd = df.parse(end);
			if (star.getTime()>endd.getTime()){//比较时间的大小
				Ajax.error(resp,"时间有误",10001);
				return;
         }
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
}






List<ExperssVo> list = e.getCheckFile(title,username,start,end,startpage,limitpage);
PageInfo<ExperssVo>pageInfo = new PageInfo<ExperssVo>(list);
Integer count = (int) pageInfo.getTotal();
System.out.println("多条件count:"+count);
Ajax.success(resp, "list","count", list,count);
}
/**
 * 审核待审核的快件
 * @param dto
 * @param req
 * @param resp
 */
@PostMapping("checkExpress.act")
public void putdocEdit(PutdocEditdto dto,HttpServletRequest req, HttpServletResponse resp) {
String status = dto.getStatus();
String fid =  dto.getEid();
String uid = dto.getUserid();
Integer yunMoney = Integer.parseInt(dto.getNewscore());


System.out.println("该文件id:"+fid);
Integer Fid = 0;
Integer Uid = 0;
try {
	Fid = Integer.parseInt(fid);
	Uid = Integer.parseInt(uid);
} catch (NumberFormatException e) {
	Ajax.error(resp, "id错误");
	e.printStackTrace();
	return;
}
Integer iStatus = 0;

try {
	iStatus = Integer.parseInt(status);
} catch (NumberFormatException e) {
	Ajax.error(resp, "状态错误",10000);
	e.printStackTrace();
	return;
}
//获得当前登录者的对象
AdminInfo admin = (AdminInfo) req.getSession().getAttribute("admin");
//登录者的id
Long aid = admin.getAdminId();
//登陆者的角色id
Long rid = admin.getRoleId();
//获得登陆者所在的网点id
NetWithAdminVo ne = n.selectNAbyAid(aid);
Integer naid = ne.getNaId();
Integer neid = ne.getNeId();

//获得快件对象
ExpressInfo einfo = e.getExpressInfo(Fid);
//获得该用户对象
UserInfo user = u.getUserByid(Uid);
//获得该快用户寄送的历史对象
UserOldInfo uo = u.selectbyuideid(Uid,Fid);

//审核时要考虑普通管理员以下包括普通管理员审核时该快件是否在同一个网点上
//不包括超级管理员时
int adminNid = naid;//相关人员所在的网点id
int logisticsNid = uo.getuArea();
if (rid>1) {
	if (adminNid!=logisticsNid) {
		Ajax.error(resp, "该快件不是本地快件无法审核(只有超级管理员才能审核)",10001);
		System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++审核人员的地点id:"+adminNid);
		System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++寄送的历史对象的地点id:"+logisticsNid);
		return;
	}
}





Integer index = e.checkExpress(Fid,iStatus);



System.out.println("修改结果:"+index);
if (index>0) {
	

	//该快件对象的审核状态
	Integer state = einfo.getcId();

	System.out.println("审核的状态:"+state);
	//当审核不通过时
	if (state==3) {
		//获得该用户的余额
		Integer score = user.getuMoney();
		System.out.println("该用户添加前余额为:"+score);
		Integer newScore = score+yunMoney;
		System.out.println("该用户添加后余额为:"+newScore);
		//将获得的积分修改它原来的余额
		if (newScore>0) {
			Integer x = u.updateUserScore(newScore,Uid);
			if(x>0) {
				System.out.println("退还余额修改成功");
			}else {
				System.out.println("退还余额修改失败");
				return;
			}
		}
		
	}
	//当审核通过时统计下快件数
	if (state==2) {
		//统计对应网点的总快件数，则需要网点id,以及统计的数量
		    Integer naidd = uo.getuArea();
		    System.out.println("历史地址:"+naidd);
			Integer count = e.countEX(naidd,state);
			System.out.println(naidd);
			System.out.println(state);
			
		//将总快件数更新到网点表
			Integer ff = n.updateNetesun(naidd,count);
			if (ff>0) {
				System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxx已统计总件");
			}else {
				System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxx未统计总件");
				return;
			}
	}
		
	
	AdminInfo admin1 = (AdminInfo) req.getSession().getAttribute("admin");
	Long aid1 = admin1.getAdminId();
	Integer cid = 5;//此为审核的操作id
	Integer logs = log.addlog(aid1,cid,checkurl);
	if (logs>0) {
		System.out.println("加入日志成功");
	}else {
		System.out.println("加入日志失败");
		return;
	}
	Ajax.success(resp);
	System.out.println("修改成功");
	return;
}else {
	Ajax.error(resp, "修改失败",10001);
	System.out.println("修改失败");
}

}
/**
 * 审核通过的快件多条件查询
 * @param dto
 * @param req
 * @param resp
 */
@GetMapping("selectSendFile.act")
private void selectSendFile(GetMyLogisticsDto dto,HttpServletRequest req, HttpServletResponse resp) {
	
	Integer startpage = Integer.parseInt(dto.getStartpage());
	Integer limitpage = Integer.parseInt(dto.getLimitpage());
	Long sendState = (long) Integer.parseInt(dto.getSendState());
	
	String start = dto.getStart();//起始日期
	String end = dto.getEnd();//结束日期
	String username = dto.getUsername();
	String title = dto.getTitle();
if (sendState==-1) {
	sendState = null;
}

if (username.equals("")) {
	username = null;
}
if (title.equals("")) {
	title = null;
}
if (start.equals("")) {
		start = null;
}
if (end.equals("")) {
	end = null;
}
if (start!=null&&end!=null) {
	DateFormat df = new SimpleDateFormat("yyyy-MM-dd");//日期格式处理
     try {
			Date star = df.parse(start);
			Date endd = df.parse(end);
			if (star.getTime()>endd.getTime()){//比较时间的大小
				Ajax.error(resp,"时间有误",10001);
				return;
         }
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
}




List<ExperssVo> list = e.selectSendFile(sendState,title,username,start,end,startpage,limitpage);
PageInfo<ExperssVo>pageInfo = new PageInfo<ExperssVo>(list);
Integer count = (int) pageInfo.getTotal();
System.out.println("多条件count:"+count);
Ajax.success(resp, "list","count", list,count);
}
/**
 * 管理员进行退单操作
 * @param dto
 * @param req
 * @param resp
 */
@PostMapping("chargeback.act")
public void chargeback(SendStateDto dto, HttpServletRequest req, HttpServletResponse resp) {
	//退单分两个步骤：1.将数据库中的寄送状态改变，2.将退单的物件的钱返还给用户
	Integer uid = Integer.parseInt(dto.getUid());//用户id
	Integer eid = Integer.parseInt(dto.getEid());//快件id
	Integer money = Integer.parseInt(dto.getMoney());//运费
	Integer sendState = 2;//修改的状态
	//获得该快用户寄送的历史对象
	UserOldInfo uo = u.selectbyuideid(uid,eid);
	//获得当前登录者的id
	AdminInfo admin = (AdminInfo) req.getSession().getAttribute("admin");
	Long aid = admin.getAdminId();
	//登陆者的角色id
	Long rid = admin.getRoleId();
	//获得登陆者所在的网点id
	NetWithAdminVo ne = n.selectNAbyAid(aid);
	Integer naid = ne.getNaId();
	
	
	//获得用户对象的寄件地址
	Integer areaid =  uo.getuArea();
		System.out.println("该快件历史所在地址"+areaid);
	
		int adminNid = naid;//相关人员所在的网点id
		int logisticsNid = uo.getuArea();
		if (rid>1) {
			if (adminNid!=logisticsNid) {
				Ajax.error(resp, "该快件不是本地快件无法退单(只有超级管理员才能退单)",10001);
				System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++审核人员的地点id:"+adminNid);
				System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++寄送的历史对象的地点id:"+logisticsNid);
				return;
			}
		}
		
		
	//1.将数据库中的寄送状态改变  改变状态 值为2 “要求退单”变为“已退单”
	Integer index = e.updateSendState(eid,sendState);
	if (index > 0) {
	//2.将退单的物件的钱返还给用户
		System.out.println("-----本次退单退还金额为:"+money+"元");
		 //获取该用户对象
		UserInfo use = u.getUserByid(uid);
		 //获取该对象的余额
		Integer oldMoney =use.getuMoney();
		System.out.println("-----该用户旧余额为:"+oldMoney);
		 //给用户还钱
		Integer newMoney = oldMoney + money;
		System.out.println("-----该用户新余额为:"+newMoney);
		Integer x = u.updateUserScore(newMoney, uid);
		if (x > 0) {
			System.out.println("退单钱已还");
		}else {
			System.out.println("退单钱未还");
			return;
		}
   //退单成功后将uid,eid,aid,sendState记录到审核寄送表
		//获得当前登录者的id
		//加入审核寄送表
		Integer flag = c.addCheckinfo(aid,eid,uid,sendState);
		if (flag>0) {
			System.out.println("已添加审核表");
		}else {
			System.out.println("未添加审核表");
			return;
		}
		Ajax.success(resp);
		System.out.println("退单操作成功");
		
		//统计一下退单快件数
		Integer count = e.countEX2(areaid,sendState);
		System.out.println("+++++++++++++++++++++++退单件数量为"+count);
		Integer ff = n.updateNetbsun(areaid,count);
		if (ff>0) {
			System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx已统计退单件");
		}else {
			System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx未统计退单件");
			return;
		}
		AdminInfo admin1 = (AdminInfo) req.getSession().getAttribute("admin");
		Long aid1 = admin1.getAdminId();
		Integer cid = 7;//此为退单的操作id
		Integer logs = log.addlog(aid1,cid,sendurl);
		if (logs>0) {
			System.out.println("加入日志成功");
		}else {
			System.out.println("加入日志失败");
			return;
		}
		return;
	} else {
		Ajax.error(resp, "退单操作失败", 10001);
		System.out.println("退单操作失败");
		return;
	}
	
}
/**
 * 管理员寄送操作
 * @param status
 * @param content
 * @param dto
 * @param req
 * @param resp
 */
@PostMapping("toSend.act")
public void toSend(String status,String content, SendStateDto dto,HttpServletRequest req, HttpServletResponse resp) {
	//发件分为两种情况 1.发送成功 2.发送失败
	Integer uid = Integer.parseInt(dto.getUid());//用户id
	Integer eid = Integer.parseInt(dto.getEid());//快件id
	Integer money = Integer.parseInt(dto.getMoney());//运费
	//获得当前登录者的id
	AdminInfo admin = (AdminInfo) req.getSession().getAttribute("admin");
	Long aid = admin.getAdminId();
	//登陆者的角色id
	Long rid = admin.getRoleId();
	//获得登陆者所在的网点id
	NetWithAdminVo ned = n.selectNAbyAid(aid);
	Integer naid = ned.getNaId();
	//获得该快用户寄送的历史对象
	UserOldInfo uo = u.selectbyuideid(uid,eid);
	//获得用户对象的寄件网点
	Integer areaid = 0;
	try {
		areaid = uo.getuArea();
	} catch (Exception e) {
		Ajax.error(resp, "areaid为空不能寄送", 10000);
		return;
	}
	
	//查询该网点的收益和网点id
	NEInfo ne = n.selectNetWorkByAreaid(areaid);
	Integer nMoney = ne.getNaMoney();
	int adminNid = naid;//相关人员所在的网点id
	int logisticsNid = uo.getuArea();
	
	
	//获得用户的对象
	UserInfo einfo = u.getUserByid(uid);
	
	System.out.println("该快件历史所在地址"+areaid);
	// 初始化选择器的值
			int iStatus = 0;

			try {
				iStatus = Integer.parseInt(status);
			} catch (NumberFormatException e) {
				Ajax.error(resp, "状态错误", 10000);
				e.printStackTrace();
				return;
			}
			if (rid>1) {
				if (adminNid!=logisticsNid) {
					Ajax.error(resp, "该快件不是本地快件无法寄送(只有超级管理员才能寄送)",10001);
					System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++审核人员的地点id:"+adminNid);
					System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++寄送的历史对象的地点id:"+logisticsNid);
					return;
				}
			}
	if (iStatus==3) {
		//可发送
		Integer index = e.updateSendState(eid,iStatus);
		if (index>0) {
			 
			String success = "寄送操作成功";
			Ajax.success(resp,"success",success);
			System.out.println("寄送操作成功");
			//将uid,eid,aid,sendState记录到审核寄送表
			
			//加入审核寄送表
			Integer flag = c.addCheckinfo(aid,eid,uid,iStatus);
			if (flag>0) {
				System.out.println("已添加审核表");
			}else {
				System.out.println("未添加审核表");
				return;
			}
	//累加收益
			
			System.out.println(areaid+"该网点旧收益为:"+nMoney);
			//把寄送的运费加入总收益中
			Integer newMoney = nMoney+money;
			System.out.println("该网点新收益为:"+newMoney);
			//将新的收益更新到数据表中
			Integer x = n.updateNetMoney(areaid,newMoney);
			if (x>0) {
				System.out.println("!!!!!!!!!!已添加收益");
			}else {
				System.out.println("!!!!!!!!!!未添加收益");
				return;
			}
			AdminInfo admin1 = (AdminInfo) req.getSession().getAttribute("admin");
			Long aid1 = admin1.getAdminId();
			Integer cid = 6;//此为寄送的操作id
			Integer logs = log.addlog(aid1,cid,sendurl);
			if (logs>0) {
				System.out.println("加入日志成功");
			}else {
				System.out.println("加入日志失败");
				return;
			}
			return;
		}else {
			Ajax.error(resp, "寄送操作失败", 10001);
			System.out.println("寄送操作失败");
			return;
		}
	}else if (iStatus==4) {
		//不可发送
		Integer index = e.updateSendState(eid,iStatus);
		if (index>0) {
			String success = "已修改为不可寄送";
			Ajax.success(resp,"success",success);
			System.out.println("已修改为不可寄送");
			//获取该用户对象
			UserInfo use = u.getUserByid(uid);
			 //获取该对象的余额
			Integer oldMoney =use.getuMoney();
			System.out.println("-----该用户旧余额为:"+oldMoney);
			 //给用户还钱
			Integer newMoney = oldMoney + money;
			System.out.println("-----该用户新余额为:"+newMoney);
			Integer x = u.updateUserScore(newMoney, uid);
			if (x > 0) {
				System.out.println("寄送失败退单钱已还");
			}else {
				System.out.println("寄送失败退单钱未还");
				return;
			}
			//将uid,eid,aid,sendState记录到审核寄送表
			
			//加入审核寄送表
			Integer flag = c.addCheckinfo(aid,eid,uid,iStatus);
			if (flag>0) {
				System.out.println("已添加审核表");
			}else {
				System.out.println("未添加审核表");
				return;
			}
			//统计一下问题快件数e.countEX(areaid,sendState);
			Integer count = e.countEX2(areaid,iStatus);
			System.out.println("+++++++++++++++++++++++问题件数量为"+count+"+++++++++++所在地址为"+areaid);
			//更新到网点表上
			Integer ff = n.updateNetpsun(areaid,count);
			if (ff>0) {
				System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxx已统计问题件");
			}else {
				System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxx未统计问题件");
				return;
			}
			AdminInfo admin1 = (AdminInfo) req.getSession().getAttribute("admin");
			Long aid1 = admin1.getAdminId();
			Integer cid = 8;//此为寄送失败的操作id
			Integer logs = log.addlog(aid1,cid,sendurl);
			if (logs>0) {
				System.out.println("加入日志成功");
			}else {
				System.out.println("加入日志失败");
				return;
			}
			return;
		}else {
			Ajax.error(resp, "寄送操作失败", 10001);
			System.out.println("寄送操作失败");
			return;
		}
	}
}
@GetMapping("getnetWorkSun.act")
private void getnetWorkSun(String kind,
		HttpServletRequest req, HttpServletResponse resp) {
	Long kid = (long) Integer.parseInt(kind);
	if (kid==0) {
		kid = null;
	}
	//x为所有网点名的集合
	//num为各个网点的收益(收益为0也要显示出来)
	
	//查询所有网点名
	List<NetWorkMoneySunVo> list = a.selectNetWorkName(kid);
	ArrayList<String> xList = new ArrayList<String>();
	ArrayList<Integer> numList = new ArrayList<Integer>();
	for (int i = 0; i < list.size(); i++) {
		xList.add(list.get(i).getNaName());
		numList.add(list.get(i).getNaMoney());
	}
	Ajax.success(resp, "x", "num", xList, numList);
	
	
}
@GetMapping("getexpressSun.act")
private void getexpressSun(GetexpressSunDto dto,HttpServletRequest req, HttpServletResponse resp) {
Long kind = (long) Integer.parseInt(dto.getKind());

Integer one = Integer.parseInt(dto.getOne());
Integer tow = Integer.parseInt(dto.getTow());
Long three = (long) Integer.parseInt(dto.getThree());
if (kind==0) {
	kind = null;
	three=(long) 0;
}
if (three==0) {
	three = null;
}

List<AdminMoneySunVo> list = a.getexpressSun(three,kind);
ArrayList<String> xList = new ArrayList<String>();
ArrayList<Integer> numList = new ArrayList<Integer>();
for (int i = 0; i < list.size(); i++) {
	xList.add(list.get(i).getaName());
	numList.add(list.get(i).getMoney());
}
Ajax.success(resp, "x", "num", xList, numList);
}


}
